package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.utils.CorrectText;
import com.mars.module.utils.GetFontUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysTextCorrectRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysTextCorrectMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysTextCorrect;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysTextCorrectService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 文字纠错记录业务层处理
 *
 * @author mars
 * @date 2024-04-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysTextCorrectServiceImpl implements ISysTextCorrectService {

    private final SysTextCorrectMapper baseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysTextCorrect add(SysTextCorrectRequest request) {
        SysTextCorrect entity = SysTextCorrect.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        //调用文本纠错接口
        CorrectText text = new CorrectText();
        String correctText = text.getCorrectText(request.getText());
        entity.setCorrectText(correctText);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysTextCorrectRequest request) {
        SysTextCorrect entity = SysTextCorrect.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysTextCorrect getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysTextCorrect> pageList(SysTextCorrectRequest request) {
        Page<SysTextCorrect> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysTextCorrect> query = this.buildWrapper(request);
        IPage<SysTextCorrect> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysTextCorrect> list(SysTextCorrectRequest request) {
        LambdaQueryWrapper<SysTextCorrect> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public void exportWord(HttpServletResponse response, List<Long> id) throws IOException {
        // 创建一个空的Word文档
        XWPFDocument document = new XWPFDocument();
        List<SysTextCorrect> sysTextCorrects = baseMapper.selectList(new QueryWrapper<SysTextCorrect>().lambda().in(SysTextCorrect::getId, id));
        for (SysTextCorrect correct : sysTextCorrects) {
            // 创建一个段落
            XWPFParagraph paragraph = document.createParagraph();
            paragraph.createRun().setText(correct.getCorrectText());
        }
        // 将文档写入到输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        document.write(out);
        byte[] bytes = out.toByteArray();
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "correctText.docx");
        // 将文档作为响应返回
        response.setHeader("Content-Disposition", "attachment; filename=correctText.docx");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        // 写入字节并清空缓冲区
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    private LambdaQueryWrapper<SysTextCorrect> buildWrapper(SysTextCorrectRequest param) {
        LambdaQueryWrapper<SysTextCorrect> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getText())) {
            query.like(SysTextCorrect::getText, param.getText());
        }
        if (StringUtils.isNotBlank(param.getCorrectText())) {
            query.like(SysTextCorrect::getCorrectText, param.getCorrectText());
        }
        return query;
    }

}
